<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/12 0012
 * Time: 17:55
 */

namespace common\models\Plug;


use common\components\DataHelper;
use yii\db\ActiveQuery;
use yii\helpers\ArrayHelper;

class Plug extends PlugBase
{
    const AUTO_CLOSE_YES = 1;
    const AUTO_CLOSE_NO = 0;

    /**
     * 创建检索条件
     * @param ActiveQuery $query
     * @param $params
     */
    public static function createSearchCondition(ActiveQuery $query, $params)
    {

        if ( @$params["name"] ) {
            $query->andWhere('locate(:name, name)', [':name'=>trim($params['name'])]);
        }

        if ( @$params["time_end"] && ($params["time_end"] = strtotime($params["time_end"])) ) {
            $query->andWhere("created_time <= :end", [
                ":end" => $params["time_end"]
            ]);
        }

        if ( !DataHelper::isEmpty(@$params["status"]) ) {
            $query->andWhere([
                "status" => $params["status"]
            ]);
        }
        return ;
    }

    public function rules()
    {
        return array_merge([
            [["start_delayed", "valid_time", "mutex_id"], "filter", "filter" => "intval"],
            ["status", "default", "value" => self::STATUS_YES]
        ], parent::rules()); // TODO: Change the autogenerated stub
    }

    public static function getAutoCloseMap($key = "ALL", $default = false)
    {
        $ret = [
            self::AUTO_CLOSE_YES => "是",
            self::AUTO_CLOSE_NO => "否",
        ];
        if ( $key === "ALL" ) {
            return $ret;
        }
        return ArrayHelper::getValue($ret, $key, $default);
    }

    public function getMutex()
    {
        return $this->hasOne(self::class, [
            "id" => "mutex_id"
        ]);
    }
}